"use strict"
const querystring = require('querystring');

const { SHA1 } = require("crypto-js");

function randString(x) {
  let s = "";
  while (s.length < x && x > 0) {
    const v = Math.random() < 0.5 ? 32 : 0;
    s += String.fromCharCode(
      Math.round(Math.random() * (122 - v - (97 - v)) + (97 - v))
    );
  }
  return s;
}

function CheckSum(AppSecret, Nonce, CurTime) {
  return SHA1(AppSecret + Nonce + CurTime);
}

const url = 'https://api.netease.im/sms/sendcode.action';

exports.format = {
    "id":'wysms',
    "name":"网易云信服务（Short Message Service）",
    "fields":{
        "appid" :{'type':'string','val':'','name':"accessKeyId"},
        "secret" :{'type':'string','val':'','name':"accessKeySecret"},
        // "expire" :{'type':'int','val':0,'name':"验证码超时(S)"},
        // "SignName" :{'type':'string','val':'','name':"SignName"},
        // "templateid" :{'type':'string','val':'','name':"TemplateCode"},
    }
};
// POST https://api.netease.im/sms/sendcode.action HTTP/1.1
// Content-Type:application/x-www-form-urlencoded;charset=utf-8


//发送验证码
exports.code = function(phone){
    if(!this.opensdk.setting || !this.opensdk.setting.appid){
        return this.error("opensdk.setting empty");
    }
    let query = {
        "mobile":phone,
    }
    let [Nonce, CurTime] = [randString(20), new Date().getTime().toString().slice(0, 10)]
    let sa = CheckSum(this.opensdk.setting.secret,Nonce,CurTime);
    let headers = {
        'AppKey':this.opensdk.setting.appid,
        'Nonce':Nonce,
        'CurTime': CurTime,
        'CheckSum':sa,
        'Content-type': "application/x-www-form-urlencoded;charset=utf-8",
        // Accept: 'application/json',
    }
    return this.library("request/post", url, querystring.stringify(query),true,headers);
}

const NAMETEST = /^[a-zA-Z0-9_-]{3,64}$/;
//登录与认证TOKEN
//user
//pass
exports.login = async function () {
    let user = this.get("phone");
    if(!user){
        return this.error("args empty");
    }
    let pass = this.get("password");
    if(!pass){
        return this.error("args empty");
    }
    // let user = '17521017960'
    // let pass = '123'

    let model = this.model.branch('openid',this.branch);
    let ret =await model.check(this.opensdk._id,user,pass);
    if(!ret){
        return this.error('phone not exist or password error');
    }
    // if(ret['status'] < 1){
    //     return this.error("账号已被禁用");
    // }
    //BOBTODO 开发者密码做加密
    if(ret['token']!=pass){
        console.log("token",ret['token']);
        console.log("pass",pass);
        return this.error('password error');
    }
    // let guid = '6423d9bc553ce2f024eab9cb';
    return ret;
}

// exports.changePassWord = async function () {
//     let user = this.get("user");
//     if(!user){
//         return this.error("user empty");
//     }
//     let pass = this.get("pass");
//     if(!pass){
//         return this.error("pass empty");
//     }

//     // let user = 17521017960
//     // let pass = '1111111'
//     // if(!NAMETEST.test(user)){
//     //     return this.error("user illegal",'a-zA-Z0-9_-')
//     // }

//     let model = this.model.branch('openid',this.branch);
// //  Model.login(opensdk,phone,password);
//     // let ret=await model.login();
//     // let ret=await model.login(user);
//     // if(!ret){
//     //     return this.error('账号不存在');
//     // }
//     // if(ret['status'] < 1){
//     //     return this.error("账号已被禁用");
//     // }
//     //BOBTODO 开发者密码做加密
//     if(ret['token']!=pass){
//         return this.error('password error');
//     }
//     // let verify_xcode = developsModel.password(pass);
//     // console.log(pass,verify_xcode,ret['xcode']);
//     // if( verify_xcode !== ret['xcode']){
//     //     return this.error('password error');
//     // }
//     let guid = '6423d9bc553ce2f024eab9cb';
//     return {guid};
// }

// curl -X POST -H 
// "AppKey: go9dnk49bkd9jd9vmel1kglw0803mgq3"
// "CurTime: 1443592222"
// "CheckSum: 9e9db3b6c9abb2e1962cf3e6f7316fcc55583f86"
// "Nonce: 4tgggergigwow323t23t"
// "Content-Type: application/x-www-form-urlencoded" 
// 'mobile=13812345678'
// 'https://api.netease.im/sms/sendcode.action'
